package top.mcwebsite.playandroid.business.qa.vm

import androidx.lifecycle.viewModelScope
import kotlinx.coroutines.launch
import top.mcwebsite.playandroid.business.qa.api.QAApiService
import top.mcwebsite.playandroid.common.network.api.NetworkService
import top.mcwebsite.playandroid.common.network.api.createApi
import top.mcwebsite.playandroid.common.network.model.ApiResult
import top.mcwebsite.playandroid.common.uiWidget.ErrorModel
import top.mcwebsite.playandroid.lib.mvi.base.BaseViewModel
import top.mcwebsite.playandroid.lib.servicemanager.core.ServiceManager

class QADetailViewModel : BaseViewModel<QADetailIntent, QADetailUiState, QADetailUiEffect>(QADetailUiState()) {

    val qaApiService = ServiceManager.getService<NetworkService>()
        .createApi<QAApiService>()


    init {
        onEach(QADetailUiState::qaId) {
            if (it != null) {
                fetchQAReplayComments(it)
            }
        }
    }

    override fun handleIntent(intent: QADetailIntent) {
        when (intent) {
            is QADetailIntent.InitQADetailIntent -> {
                setUiState { copy(qaId = intent.qaId) }
            }
            is QADetailIntent.ClickAnswerItemIntent -> {
                sendUiEffect(QADetailUiEffect.GoAnswerPagerUiEffect(intent.index))
            }
            is QADetailIntent.BackIntent -> {
                sendUiEffect(QADetailUiEffect.BackUiEffect)
            }
        }
    }

    private fun fetchQAReplayComments(qaId: Long) {
        viewModelScope.launch {
            when (val result = qaApiService.qaComment(qaId)) {
                is ApiResult.Success -> {
                    setUiState {
                        copy(replayComments = result.data.data?.datas ?: emptyList())
                    }
                }
                is ApiResult.Failure -> {
                    setUiState { copy(errorModel = ErrorModel(result.cause) {
                        setUiState { copy(errorModel = null) }
                        fetchQAReplayComments(qaId)
                    }) }
                }
            }
        }
    }
}